<?php
class ModelTotalReward extends Model {
	public function getTotal(&$total_data, &$total, &$taxes) {
		if (isset($this->session->data['reward'])) {
			$this->language->load('total/reward');
			
			$points = $this->customer->getRewardPoints();
			
			if ($this->session->data['reward'] <= $points) {
				$discount_total = 0;
				
				$points_total = 0;
				$tax_points_total = 0;
				foreach ($this->cart->getProducts() as $product) {
					if ($product['points']) {
						$points_total += $product['points'];
						if ($product['tax_class_id']) {
							$tax_points_total += $product['points'];
						}
					}
				}
				
				$points_total = min($this->session->data['reward'], $points_total);
				$tax_points_total = min($points_total, $tax_points_total);
				$discount_total = $points_total * C('reward_ratio');
				
				//tax
				if ($tax_points_total) {
					foreach ($this->cart->getProducts() as $product) {
						if ($product['points'] && $product['tax_class_id']) {
							$product_points = 0;
							if ($product['points'] >= $tax_points_total) {
								$product_points = $tax_points_total;
							}
							else {
								$product_points = $product['points'];
							}
							$tax_points_total -= $product_points;
							
							$tax_rates = $this->tax->getRates($product_points * C('reward_ratio'), $product['tax_class_id']);
									
							foreach ($tax_rates as $tax_rate) {
								if ($tax_rate['type'] == 'P') {
									$taxes[$tax_rate['tax_rate_id']] -= $tax_rate['amount'];
								}
							}
							
							if ($tax_points_total <= 0) break;
						}
					}
				}
				
				//total
				$total_data[] = array(
					'code'       => 'reward',
        			'title'      => sprintf($this->language->get('text_reward'), $this->session->data['reward']),
	    			'text'       => $this->currency->format(-$discount_total),
        			'value'      => -$discount_total,
					'sort_order' => C('reward_sort_order')
      			);

				$total -= $discount_total;
			} 
		}
	}
	
	public function confirm($order_info, $order_total) {
		$this->language->load('total/reward');
		
		$points = 0;
		
		$start = strpos($order_total['title'], '(') + 1;
		$end = strrpos($order_total['title'], ')');
		
		if ($start && $end) {  
			$points = substr($order_total['title'], $start, $end - $start);
		}	
		
		if ($points) {
			$this->db->query("INSERT INTO @@customer_reward SET customer_id = '" . (int)$order_info['customer_id'] . "', description = '" . ES(sprintf($this->language->get('text_order_id'), (int)$order_info['order_id'])) . "', points = '" . (float)-$points . "', date_added = '{$GLOBALS['V5_NOW']}'");				
		}
	}		
}
?>